<template>
  <div class="pager">
    <a href="" class="pager-item"
    :class="{
        disabled:page==1
    }"
    @click.prevent="handlePage(1)">首页</a>
    <a href="" class="pager-item"
    :class="{
        disabled:page==1
    }"
    @click.prevent="handlePage(page-1)">上一页</a>


    <a href="" class="pager-item" v-for="n in number" :key="n"
    :class="{
        active:n === page
    }"
    @click.prevent="handlePage(n)"
    >{{n}}</a>

    <a href="" class="pager-item"
    :class="{
        disabled:page==pageNumber
    }"
    @click.prevent="handlePage(page+1)">下一页</a>

    <a href="" class="pager-item"
    :class="{
        disabled:page==pageNumber
    }"
    @click.prevent="handlePage(pageNumber)">尾页</a>
    <span class="pager-text">
        <i>{{page}}</i>
        /
        <i>{{pageNumber}}</i>
    </span>
  </div>
</template>

<script>
// 分页的数据都应该是传过来的
export default {
    props:{
        page:{ //当前页码
            type:Number,
            default:1
        },
        limit:{ //每页显示数量
            type:Number,
            default:10
        },
        total:{ //总共有多少条数据
            type:Number,
            default:10
        },
        panelNumber:{
            type:Number,
            default:10
        }
    },
    computed: {
        pageNumber(){
            return Math.ceil(this.total / this.limit);
        },
        minNumber(){
            var n = 1;
            n = this.page - this.panelNumber / 2;
            if(n < 1){
                n = 1;
            }
            return n;
        },
        maxNumber(){
            var n = 1;
            n = this.minNumber + this.panelNumber - 1;
            if(n > this.pageNumber){
                n = this.pageNumber;
            }
            return n;
        },
        number(){
            var num = [];
            for (let i = this.minNumber; i <= this.maxNumber; i++) {
                num.push(i);
                
            }
            return num;
        }
    },
    methods: {
        handlePage(newPage){
            // 不能直接修改props属性的值
            // this.page = newPage;

            if(newPage < 1){
                newPage = 1;
            }
            if(newPage > this.pageNumber){
                newPage = this.pageNumber;
            }

            this.$emit("changePage",newPage);
        }
    },
};
</script>

<style scoped>
.pager {
  text-align: center;
  margin: 20px 0;
}

.pager .pager-item {
  display: inline-block;
  padding: 5px 7px;
  border: 1px solid #ccc;
  margin: 8px;
  cursor: pointer;
  color: rgb(96, 96, 224);
}

.pager .pager-item.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.pager .pager-item.active {
  color: #f40;
  border: none;
  cursor: auto;
}
</style>
